<template>
  <entity-view
    :operator-type="operatorType"
    :model="beanInfo"
    @submit="submit"
    :rules="rules"
    ref="form"
  >
    <div class="sub-content-flex">
      <form-item
        label="平台代码"
        v-model="beanInfo.platMchntNo"
        prop="platMchntNo"
        disabled
      ></form-item>
      <form-item
        label="平台名称"
        v-model="beanInfo.platMchntName"
        prop="platMchntName"
      ></form-item>
      <form-item
        label="平台所属机构"
        v-model="beanInfo.manageInstId"
        prop="manageInstId"
        inputType="select"
        :options="manageInstIdList"
        @change="(value) => handleChange(value, 'manageInstId')"
      ></form-item>
      <form-item
        label="平台商户证件类型"
        v-model="beanInfo.licenceType"
        prop="licenceType"
        inputType="select"
        :options="licenceTypeList"
        @change="(value) => handleChange(value, 'licenceType')"
      >
      </form-item>
      <form-item
        label="平台商户证件号码"
        v-model="beanInfo.manageInstLicenceCode"
        prop="manageInstLicenceCode"
        :maxLength="32"
      ></form-item>
      <form-item
        label="法人证件类型"
        v-model="beanInfo.artifCertType"
        prop="artifCertType"
        inputType="select"
        :options="artifCertTypeList"
        @change="(value) => handleChange(value, 'artifCertType')"
      ></form-item>
      <form-item
        label="法人证件编号"
        v-model="beanInfo.artifCertNo"
        prop="artifCertNo"
        :maxLength="32"
      ></form-item>
      <form-item
        label="法人"
        v-model="beanInfo.artifName"
        prop="artifName"
        :maxLength="20"
      ></form-item>
      <form-item
        label="法人联系方式"
        v-model="beanInfo.artifMobile"
        prop="artifMobile"
        :maxLength="20"
      ></form-item>
      <form-item
        label="法人电子邮件"
        v-model="beanInfo.artifEmail"
        prop="artifEmail"
        :maxLength="64"
      ></form-item>
      <form-item
        label="平台联系人"
        v-model="beanInfo.contactName"
        prop="contactName"
      ></form-item>
      <form-item
        label="平台联系人电话"
        v-model="beanInfo.contactPhone"
        prop="contactPhone"
        :maxLength="20"
      ></form-item>
      <form-item
        label="平台联系人邮箱"
        v-model="beanInfo.contactEmaiil"
        prop="contactEmaiil"
        :maxLength="64"
      ></form-item>
      <form-item
        label="平台网络域名"
        v-model="beanInfo.mchntNetworkDomain"
        prop="mchntNetworkDomain"
        :maxLength="128"
      ></form-item>
      <form-item
        label="ICP备案"
        v-model="beanInfo.icpRecordNo"
        prop="icpRecordNo"
        :maxLength="32"
      ></form-item>
      <form-item label="IP地址" v-model="beanInfo.ip" prop="ip"
                 :maxLength="32"></form-item>
      <form-item
        label="收银台签约类型"
        inputType="select"
        v-model="beanInfo.signType"
        prop="signType"
        :options="signTypeList"
        @change="(value) => handleChange(value, 'signType')"
      ></form-item>
      <form-item
        label="企业注册类型"
        inputType="select"
        v-model="beanInfo.enterRegisterType"
        prop="enterRegisterType"
        :options="enterRegisterTypeList"
        @change="(value) => handleChange(value, 'enterRegisterType')"
      ></form-item>
      <form-item
        label="经营范围"
        inputType="select"
        v-model="beanInfo.managementScope"
        prop="managementScope"
        :options="managementScopeList"
        @change="(value) => handleChange(value, 'managementScope')"
      ></form-item>
      <form-item
        label="行业类别"
        v-model="beanInfo.industryType"
        prop="industryType"
        inputType="select"
        :options="industryTypeList"
        @click.native="getIndustryTypeList()"
        @change="(value) => handleChange(value, 'industryType')"
      ></form-item>
      <form-item
        label="收银台名称"
        v-model="beanInfo.cashDeskName"
        prop="cashDeskName"
        :maxLength="128"
      ></form-item>
      <form-item label="平台商户logo">
        <a-upload
          list-type="picture-card"
          :show-upload-list="false"
          :data="{'isup':1}"
          :before-upload="beforeUpload"
          :customRequest="selfUpload"
        >
          <div  v-if="this.imageUrl !== ''">
            <img :src="this.imageUrl" width="100px" height="100px">
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>查看大图</span>
              </template>
              <a-icon :type="'eye'" theme="twoTone" twoToneColor="#4a9ff5" @click="handlePreview"/>
            </a-tooltip>
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>清除图片</span>
              </template>
              <a-icon :type="'delete'" theme="twoTone" twoToneColor="#4a9ff5" @click="deleteImg" />
            </a-tooltip>
          </div>
          <div v-if="this.imageUrl === ''">
            <a-icon :type="'plus'"/>
            <div class="ant-upload-text">上传</div>
          </div>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="this.imageUrl" />
          </a-modal>
        </a-upload>
      </form-item>
      <form-item
        label="是否支持授信交易"
        v-model="beanInfo.grantCreditFlag"
        prop="grantCreditFlag"
        inputType="select"
        :options="grantCreditFlagList"
        @change="(value) => handleChange(value, 'grantCreditFlag')"
      ></form-item>
      <form-item
        label="是否支持担保交易"
        v-model="beanInfo.guaranteeFlag"
        prop="guaranteeFlag"
        inputType="select"
        :options="guaranteeFlagList"
        @change="(value) => handleChange(value, 'guaranteeFlag')"
      ></form-item>
      <form-item
        label="是否要向微信进件"
        v-model="beanInfo.isWechatEntryFlag"
        prop="isWechatEntryFlag"
        inputType="select"
        :options="isWechatEntryFlagList"
        @change="(value) => handleChange(value, 'isWechatEntryFlag')"
      ></form-item>
      <form-item
        label="停用原因"
        v-model="beanInfo.stopReason"
        prop="stopReason"
        :maxLength="128"
        inputType="textarea"
        v-if="operatorType === 'view' || operatorType === 'stop'"
      ></form-item>
      <form-item
        label="注销原因"
        v-model="beanInfo.cancelReason"
        prop="cancelReason"
        :maxLength="128"
        inputType="textarea"
        :valid="operatorType === 'cancel'"
        v-if="operatorType === 'view' || operatorType === 'cancel'"
      ></form-item>
      <template v-if="beanInfo.isWechatEntryFlag === '1'">
        <form-item
          label="微信通道"
          v-model="beanInfo.channelType"
          prop="channelType"
          inputType="select"
          :options="channelTypeList"
          @change="(value) => handleChange(value, 'channelType')"
        ></form-item>
        <form-item
          label="APP支付APPID"
          v-model="beanInfo.appId"
          prop="appId"
        ></form-item>
        <form-item
          label="APP支付密钥"
          v-model="beanInfo.appSecretKey"
          prop="appSecretKey"
        ></form-item>
        <form-item
          label="小程序支付APPID"
          v-model="beanInfo.miniAppId"
          prop="miniAppId"
        ></form-item>
        <form-item
          label="小程序支付密钥"
          v-model="beanInfo.miniSecretKey"
          prop="miniSecretKey"
        ></form-item>
      </template>
    </div>
  </entity-view>
</template>
<script>
  import EntityView from "../../../../components/common/entityView/EntityView.vue";
  import FormItem from "../../../../components/common/entityView/FormItem.vue";

  export default {
    name: "PlatMchntOperation",
    components: {
      EntityView,
      FormItem,
    },
    props: {
      query: Object,
    },

    data() {
      return {
        instId: "",
        loading: false,
        pageInfo: {},
        modalTitle: "",
        operatorType: "add",
        modalVisible: true,
        beanInfo: {
          platMchntNo: "",
          logoPath: "",
        },
        rules: {
          platMchntNo: [{required: true, message: "必填", trigger: "blur"}],
          platMchntName: [{required: true, message: "必填", trigger: "blur"}],
          manageInstId: [{required: true, message: "必填", trigger: "blur"}],
          licenceType: [{required: true, message: "必填", trigger: "blur"}],
          artifCertType: [{required: true, message: "必填", trigger: "blur"}],
          artifCertNo: [{required: true, message: "必填", trigger: "blur"},{ pattern: '^[a-zA-Z1-9][a-zA-Z0-9]{0,30}$', message: '请输入正确的证件号码' }],
          artifMobile: [{required: true, message: "必填", trigger: "blur"},{pattern:'^1[3-9]{1}[0-9]{9}$', message: '请输入正确的手机号'}],
          artifName: [{required: true, message: "必填", trigger: "blur"}],
          contactName: [{required: true, message: "必填", trigger: "blur"}],
          contactPhone: [{required: true, message: "必填", trigger: "blur"},{ pattern:/^1\d{10}$/ , message: '请输入有效的手机号码', trigger: 'blur' }],
          mchntNetworkDomain: [{required: true, message: "必填", trigger: "blur"}],
          icpRecordNo: [{required: true, message: "必填", trigger: "blur"}],
          ip: [{required: true, message: "必填", trigger: "blur"}],
          signType: [{required: true, message: "必填", trigger: "blur"}],
          enterRegisterType: [{required: true, message: "必填", trigger: "blur"}],
          managementScope: [{required: true, message: "必填", trigger: "blur"}],
          industryType: [{required: true, message: "必填", trigger: "blur"}],
          isWechatEntryFlag: [{required: true, message: "必填", trigger: "blur"}],
          contactEmaiil: [{ pattern: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, message: "请输入有效的邮箱", trigger: "blur" }],
          artifEmail: [{ pattern: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, message: "请输入有效的邮箱", trigger: "blur" }],
          stopReason: [{required: true, message: '必填', trigger: 'blur'}],
          cancelReason: [{required: true, message: '必填', trigger: 'blur'}],
        },
        manageInstIdList: [],
        managementScopeList: [],
        industryTypeList: [],
        licenceTypeList: [
          {value: "00", name: "营业执照"},
          {value: "01", name: "机构信用代码证"},
          {value: "02", name: "民办非企业登记证书"},
          {value: "03", name: "全国组织机构代码证"},
          {value: "04", name: "事业单位法人证书"},
          {value: "05", name: "境外企业证书"},
          {value: "06", name: "社会团体法人登记证书"},
          {value: "07", name: "工会法人资格证书"},
          {value: "08", name: "政府批文"},
          {value: "09", name: "预先核准通知书"},
          {value: "10", name: "其他批文或证明"},
          {value: "11", name: "贷款卡号"},
          {value: "99", name: "其他"},
        ],
        artifCertTypeList: [
          {value: "01", name: "身份证"},
          {value: "02", name: "军官证"},
          {value: "03", name: "护照"},
          {value: "04", name: "户口簿"},
          {value: "05", name: "士兵证"},
          {value: "06", name: "港澳来往内地通行证"},
          {value: "07", name: "台湾同胞来往内地通行证"},
          {value: "08", name: "临时身份证"},
          {value: "09", name: "外国人居留证"},
          {value: "10", name: "警官证"},
          {value: "99", name: "其他"},
        ],
        signTypeList: [
          {value: "00", name: "银行"},
          {value: "01", name: "平台"},
        ],
        enterRegisterTypeList: [
          {value: "01", name: "小微商户"},
          {value: "02", name: "个体工商户"},
          {value: "03", name: "企业"},
          {value: "04", name: "党政机关及事业单位"},
          {value: "99", name: "其他组织"},
        ],
        grantCreditFlagList: [
          {value: "0", name: "否"},
          {value: "1", name: "是"},
        ],
        guaranteeFlagList: [
          {value: "0", name: "否"},
          {value: "1", name: "是"},
        ],
        isWechatEntryFlagList: [
          {value: "0", name: "否"},
          {value: "1", name: "是"},
        ],
        channelTypeList: [],
        imageUrl: "",
        previewVisible: false,

      };
    },
    methods: {
      handleCancel() {
        this.previewVisible = false;
      },
      deleteImg(e) {
        this.imageUrl = '';
        this.beanInfo.logoPath = '';
        e.stopPropagation();
      },

      async selfUpload({action, file, onSuccess, onError, onProgress}) {
        const formData = new FormData();
        formData.append('imgFile', file);
        formData.append('imageType', "03");
        formData.append('instId', this.instId);
        formData.append('mchntNo', this.beanInfo.platMchntNo);
        const res = await this.$upload(
          "/admin/mcmp/bMchntImageInfo/uploadBomp",formData
        );
        if (res.data.code === "100000") {
          this.imageUrl = res.data.data.imageData;
          this.beanInfo.logoPath = res.data.data.imageLocalPath;
          this.$message.success("上传logo成功！");
          return true;
        } else {
          this.$message.error(res.data.data.respDesc);
          return false;
        }
      },
      async getImage() {
        const params = {
          imageLocalPath: this.beanInfo.logoPath,
          imgId: "1",
          imageType: "03",
          instId: this.instId,
        };
        const res = await this.$get(
          "/admin/mcmp/bMchntImageInfo/getBompImg",params
        );
        if (res.data.code === "100000") {
          this.imageUrl = res.data.data.imageData;
          return true;
        } else {
          this.$message.error(res.data.data.respDesc);
          return false;
        }
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/bmp'
        if (!isJPG) {
          this.$message.error('请上传图片文件');
        }
        return isJPG;
      },
      async handlePreview(e) {
        this.previewVisible = true;
        e.stopPropagation();
      },
      handleChange(value, param) {
        this.beanInfo[param] = value;
        if (param === 'managementScope') {
          this.beanInfo.industryType = '';
        }
      },
      warning() {
        const h = this.$createElement;
        this.$warning({
          title: '提示',
          content: h('div', {}, [
            h('p', '请先选择经营范围'),
          ]),
          onOk() {},
        });
      },
      async submit() {
        let res;
        switch (this.operatorType) {
          case "add":
            res = await this.add();
            break;
          case "edit":
            res = await this.edit();
            break;
          case "view":
            res = true;
            break;
          case "use":
            res = await this.changeStatus(this.operatorType);
            break;
          case "stop":
            res = await this.changeStatus(this.operatorType);
            break;
          case "cancel":
            res = await this.changeStatus(this.operatorType);
            break;
          default:
            break;
        }
        return res;
      },
      async add() {
        const res = await this.$refs.form.validate();
        if (res) {
          const params = {
            ...this.beanInfo,
            optFlag: "add",
          };
          const res = await this.$post("/admin/merParam/platMchntInfo/edit", params);
          if (res.status === 200) {
            this.$message.success("保存成功！");
            return true;
          } else {
            this.$message.error(res.data.message);
            return false;
          }
        }
      },
      async edit() {
        const res = await this.$refs.form.validate();
        if (res) {
          const params = {
            ...this.beanInfo,
            optFlag: "upd",
          };
          const res = await this.$post("/admin/merParam/platMchntInfo/edit", params);
          if (res.status === 200) {
            this.$message.success("保存成功！");
            return true;
          } else {
            this.$message.error(res.data.message);
            return false;
          }
        }
      },
      async changeStatus(optFlag) {
        const res = await this.$refs.form.validate();
        if (res) {
          const params = {
            id: this.beanInfo.id,
            ...this.beanInfo,
            optFlag: optFlag,
          };
          const res = await this.$post("/admin/merParam/platMchntInfo/edit", params);
          if (res.status === 200) {
            this.$message.success("保存成功！");
            return true;
          } else {
            this.$message.error(res.data.message);
            return false;
          }
        }
      },
      resetFields() {
        return this.$refs.form && this.$refs.form.resetFields();
      },
      setOperatorType(type) {
        this.operatorType = type;
      },
      async setBeanInfo({...beanInfo}, instId) {
        this.imageUrl = '';
        if(this.operatorType !== 'add'){
          this.beanInfo = beanInfo;
        }
        this.instId = instId;
        await this.getInstIdOrganizationList();
        await this.getManagementScopeList();
        await this.getChannelCfg();
        if (this.operatorType === 'add') {
          await this.getEditList()
          return
        }
        await this.getOne();
        await this.getIndustryTypeList();
      },
      async getOne() {
        try {
          const res = await this.$get("/admin/merParam/platMchntInfo/edit", {
            id: this.beanInfo.id,
            optFlag: "detail",
          });
          this.beanInfo = res.data.entity || {};
          if(typeof this.beanInfo.logoPath !== "undefined" && this.beanInfo.logoPath !== ""){
            this.getImage();
          }
        } catch (e) {
          console.error(e);
        }
      },
      async getEditList() {
        try {
          const res = await this.$get("/admin/merParam/platMchntInfo/edit", {
            optFlag: "add",
            instId: this.instId,
          });
          if (res.status === 200) {
            this.beanInfo = res.data.entity || {};
          }
        } catch (e) {
          console.error(e);
        }
      },
      async getInstIdOrganizationList() {
        try {
          const res = await this.$get("/admin/merParam/UpmpOrganization/instIdOrganizationSelect2List", {
            q: encodeURIComponent(`&${this.instId}`)
          });
          if (res.status === 200) {
            this.manageInstIdList = res.data.results.map(i => {
              i.value = i.id
              return i
            })
          }
        } catch (e) {
          console.error(e);
        }
      },
      async getManagementScopeList() {
        try {
          const res = await this.$get("/admin/mcmp/bMchntBaseInfo/unionMerGrpSelect2List", {
            q: encodeURIComponent(`&${this.instId}`)
          });
          if (res.status === 200) {
            this.managementScopeList = res.data.rows.map(i => {
              i.name = i.grpNo + ' - ' + i.grpDesc
              i.value = i.grpNo
              return i
            })
          }
        } catch (e) {
          console.error(e);
        }
      },
      async getIndustryTypeList() {
        try {
          if (typeof this.beanInfo.managementScope === 'undefined') {
            this.warning();
            return;
          }
          const res = await this.$get("/admin/mcmp/bMchntBaseInfo/indusSelect2List", {
            q: encodeURIComponent(`&${this.beanInfo.managementScope}`)
          });
          if (res.status === 200) {
            this.industryTypeList = res.data.rows.map(i => {
              i.name = i.industryType + ' - ' + i.industryDesc
              i.value = i.industryType
              return i
            })
          }
        } catch (e) {
          console.error(e);
        }
      },
      async getChannelCfg() {
        try {
          const res = await this.$get("/admin/igas/pDstChannelCfg/select2List", {
            q: encodeURIComponent(`&${this.instId}&UPWX`)
          });
          if (res.status === 200) {
            this.channelTypeList = res.data.map(i => {
              i.value = i.id
              return i
            }) || {};
          }
        } catch (e) {
          console.error(e);
        }
      },
    },
  };
</script>
<style lang="less" scoped>
  @import "../../../../../static/less/Common";

  .subtitle {
    width: 100%;
    font-size: 18px;
    margin-bottom: 10px;
  }

  .sub-content-flex {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .sub-content-block {
    display: block;
    flex-wrap: wrap;
    width: 100%;
  }
</style>
